package com.twu.biblioteca;

import com.twu.biblioteca.commands.*;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class BibliotecaApp {
    public static final String WELCOME_MESSAGE = "Welcome to Biblioteca!";
    public static final String INVALID_OPTION_MESSAGE = "Select a valid option!";

    public static void main(String[] args) {
        BibliotecaApp app = new BibliotecaApp(System.in, System.out, new Biblioteca());
        Scanner scanner = new Scanner(System.in);

        boolean isQuitting;
        do {
            System.out.print("Please select an option: ");
            isQuitting = app.runCommand(scanner.next());
        } while (!isQuitting);
    }

    private PrintStream output;
    private InputStream input;
    private Biblioteca biblioteca;
    private LinkedHashMap<String, BibliotecaCommand> commands;

    public BibliotecaApp(InputStream input, PrintStream output, Biblioteca biblioteca) {
        this.input = input;
        this.output = output;
        this.biblioteca = biblioteca;

        this.commands = new LinkedHashMap<String, BibliotecaCommand>();
        this.commands.put("1", new BookListCommand(input, output, biblioteca));
        this.commands.put("2", new BookCheckoutCommand(input, output, biblioteca));
        this.commands.put("3", new ReturnCommand(input, output, biblioteca));
        this.commands.put("4", new MovieListCommand(input, output, biblioteca));
        this.commands.put("5", new MovieCheckoutCommand(input, output, biblioteca));
        this.commands.put("6", new LoginCommand(input, output, biblioteca));
        this.commands.put("7", new UserInformationCommand(input, output, biblioteca));
        this.commands.put("0", new QuitCommand(input, output, biblioteca));

        output.println(WELCOME_MESSAGE);
        output.println(getMainMenu());
    }

    public String getMainMenu() {
        StringBuilder builder = new StringBuilder();
        builder.append("--------------------------\n");
        builder.append("Main Menu\n");
        builder.append("--------------------------\n");

        for (Map.Entry<String, BibliotecaCommand> element : commands.entrySet()) {
            builder.append(element.getKey() + ". " + element.getValue().getDescription() + "\n");
        }

        builder.append("\n--------------------------\n");

        return builder.toString();
    }

    public boolean runCommand(String command) {
        BibliotecaCommand commandObject = commands.get(command);

        if (commandObject == null) {
            output.println(INVALID_OPTION_MESSAGE);
            return false;
        }

        return commandObject.run();
    }
}
